package mall.promotion;

import mall.pojo.ProductDO;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * 促销活动策略 管理器
 * @author zmy
 */
public class PromotionManager {
    private final List<PromotionStrategy> strategies = new ArrayList<>();

    public PromotionManager() {}

    /** 新增促销活动 */
    public void addStrategy(PromotionStrategy strategy) {
        boolean match = strategies.stream().anyMatch(s -> s.getId().equals(strategy.getId()));
        if (match) {
            System.out.println("活动ID重复！\n");
        } else {
            strategies.add(strategy);
        }
    }

    /** 是否启用策略 */
    public void setStrategies(String promotionId, boolean enabled) {
        strategies.stream()
                .filter(s -> s.getId().equals(promotionId))
                .forEach(s -> s.setEnabled(enabled));
    }

    /** 新增活动中的商品 */
    public void addPromotionProduct(String promotionId, List<String> productIdList) {
        Optional<PromotionStrategy> find = strategies.stream()
                .filter(s -> s.getId().equals(promotionId))
                .findFirst();
        find.ifPresentOrElse(
                promotionStrategy -> {
                    promotionStrategy.addProduct(productIdList);
                    System.out.println("添加成功！\n");
                }, () -> {
                    System.out.println("活动不存在！\n");
                }
        );
    }
    /** 移除活动中的商品 */
    public void removePromotionProduct(String promotionId, List<String> productIdList) {
        Optional<PromotionStrategy> find = strategies.stream()
                .filter(s -> s.getId().equals(promotionId))
                .findFirst();
        find.ifPresentOrElse(
                promotionStrategy -> {
                    promotionStrategy.removeProduct(productIdList);
                    System.out.println("添加成功！\n");
                }, () -> {
                    System.out.println("活动不存在！\n");
                }
        );
    }

    /**
     * 计算总共满减的金额
     * @param shopCar   购物车
     * @return  满减的金额
     */
    public double applyPromotions(List<ProductDO> shopCar) {
        // 按照优先级排序，获得所有生效的活动策略
        List<PromotionStrategy> activeStrategies = strategies.stream()
                .filter(PromotionStrategy::isEnabled)
                .sorted(Comparator
                        .comparingInt(PromotionStrategy::getPriority)
                        .thenComparingInt(e -> Integer.parseInt(e.getPromotionType())).reversed()
                )
                .toList();

        double totalReduction = 0;
        for (PromotionStrategy strategy : activeStrategies) {
            if (strategy.isApplicable(shopCar)) {
                totalReduction += strategy.apply(shopCar);
            }
        }

        return totalReduction;
    }

    /** 查看所有的优惠活动 */
    public void showPromotions() {
        strategies.forEach(System.out::println);
        System.out.println();
    }
}
